package com.luckyframe.project.jmeter.jmeterJarMgt.controller;

import com.google.common.base.Joiner;
import com.luckyframe.common.utils.file.FileUploadUtils;
import com.luckyframe.common.utils.poi.ExcelUtil;
import com.luckyframe.framework.aspectj.lang.annotation.Log;
import com.luckyframe.framework.aspectj.lang.enums.BusinessType;
import com.luckyframe.framework.config.JmeterConfig;
import com.luckyframe.framework.config.LuckyFrameConfig;
import com.luckyframe.framework.web.controller.BaseController;
import com.luckyframe.framework.web.domain.AjaxResult;
import com.luckyframe.framework.web.page.TableDataInfo;
import com.luckyframe.project.jmeter.jmeterJarCaseRel.domain.JmeterJarCaseRel;
import com.luckyframe.project.jmeter.jmeterJarCaseRel.service.IJmeterJarCaseRelService;
import com.luckyframe.project.jmeter.jmeterJarMgt.domain.JarCaseList;
import com.luckyframe.project.jmeter.jmeterJarMgt.domain.JmeterJarMgt;
import com.luckyframe.project.jmeter.jmeterJarMgt.service.IJmeterJarMgtService;
import com.luckyframe.project.jmeter.jmeterTestCase.domain.JmeterTestCase;
import com.luckyframe.project.jmeter.jmeterTestCase.service.IJmeterTestCaseService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * jmx脚本依赖jar包管理 信息操作处理
 * 
 * @author lancelot
 * @date 2020-09-27
 */
@Controller
@RequestMapping("/jmeter/jmeterJarMgt")
public class JmeterJarMgtController extends BaseController
{
    private String prefix = "jmeter/jmeterJarMgt";
	
	@Autowired
	private IJmeterJarMgtService jmeterJarMgtService;

	@Autowired
	private IJmeterTestCaseService jmeterTestCaseService;

	@Autowired
	private IJmeterJarCaseRelService jmeterJarCaseRelService;

	@Autowired
	private JmeterConfig jmeterConfig;

	@RequiresPermissions("jmeter:jmeterJarMgt:view")
	@GetMapping()
	public String jmeterJarMgt()
	{
	    return prefix + "/jmeterJarMgt";
	}


	@GetMapping("/selectTestCase")
	public String projectPlanCase(@RequestParam("jarId") Long jarId, ModelMap mmap)
	{
		List<JmeterTestCase> cases = jmeterJarMgtService.selectRelatedCases(jarId);
		if(CollectionUtils.isNotEmpty(cases)){
			mmap.put("relCaseIdList",cases.stream().
					filter(Objects::nonNull).
					map(JmeterTestCase::getId).collect(toList()));
		}else{
			mmap.put("relCaseIdList",new ArrayList<>());
		}
		mmap.put("cases", cases);
		return prefix+"/selectTestCase";
	}


	/**
	 * 保存测试计划用例操作
	 * @author Seagull
	 * @date 2019年9月30日
	 */
	@RequestMapping(value = "/saveJarCase",method=RequestMethod.POST,consumes="application/json")
	@ResponseBody
	public AjaxResult savePlanCase(@RequestBody JarCaseList jarCaseList)
	{

		jmeterJarCaseRelService.deleteByJarId(jarCaseList.getJarId().intValue());
		List<Long> relCaseIdList = jarCaseList.getCaseIdList();
		if(CollectionUtils.isNotEmpty(relCaseIdList)){
			for (Long caseId : relCaseIdList) {
				JmeterJarCaseRel jarCaseRel=new JmeterJarCaseRel();
				jarCaseRel.setRelJarId(jarCaseList.getJarId().longValue());
				jarCaseRel.setRelCaseId(caseId);
				jmeterJarCaseRelService.insertJmeterJarCaseRel(jarCaseRel);
			}
		}
		return toAjax(1);
	}



	/**
	 * 查询jmx脚本依赖jar包管理列表
	 */
	@RequiresPermissions("jmeter:jmeterJarMgt:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(JmeterJarMgt jmeterJarMgt)
	{
		startPage();
        List<JmeterJarMgt> list = jmeterJarMgtService.selectJmeterJarMgtList(jmeterJarMgt);

        if(CollectionUtils.isNotEmpty(list)){
			for (JmeterJarMgt jarMgt : list) {
				if(Objects.equals(jarMgt.getGlobal(),1)){
					continue;
				}

				List<String> caseNames = jmeterJarMgtService.selectRelatedCaseNames(jarMgt.getId().longValue());
				if(CollectionUtils.isNotEmpty(caseNames)){
					caseNames=caseNames.stream().filter(Objects::nonNull).collect(toList());
					jarMgt.setCaseNames(Joiner.on(",").join(caseNames));
				}
			}
		}

		return getDataTable(list);
	}
	
	
	/**
	 * 导出jmx脚本依赖jar包管理列表
	 */
	@RequiresPermissions("jmeter:jmeterJarMgt:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(JmeterJarMgt jmeterJarMgt)
    {
    	List<JmeterJarMgt> list = jmeterJarMgtService.selectJmeterJarMgtList(jmeterJarMgt);
        ExcelUtil<JmeterJarMgt> util = new ExcelUtil<JmeterJarMgt>(JmeterJarMgt.class);
        return util.exportExcel(list, "jmeterJarMgt");
    }
	
	/**
	 * 新增jmx脚本依赖jar包管理
	 */
	@GetMapping("/add")
	public String add(ModelMap modelMap)
	{

		List<JmeterTestCase> cases = jmeterTestCaseService.selectJmeterTestCaseList(new JmeterTestCase());

		modelMap.put("cases",cases);
		return prefix + "/add";
	}
	
	/**
	 * 新增保存jmx脚本依赖jar包管理
	 */
	@RequiresPermissions("jmeter:jmeterJarMgt:add")
	@Log(title = "jmx脚本依赖jar包管理", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(@RequestBody JmeterJarMgt jmeterJarMgt)
	{
		int i = jmeterJarMgtService.insertJmeterJarMgt(jmeterJarMgt);
		List<Long> relCaseIdList = jmeterJarMgt.getRelCaseIdList();
		if(CollectionUtils.isNotEmpty(relCaseIdList)){
			for (Long caseId : relCaseIdList) {
				JmeterJarCaseRel jarCaseRel=new JmeterJarCaseRel();
				jarCaseRel.setRelJarId(jmeterJarMgt.getId().longValue());
				jarCaseRel.setRelCaseId(caseId);
				jmeterJarCaseRelService.insertJmeterJarCaseRel(jarCaseRel);
			}
		}

		return toAjax(i);
	}

	/**
	 * 修改jmx脚本依赖jar包管理
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap)
	{
		JmeterJarMgt jmeterJarMgt = jmeterJarMgtService.selectJmeterJarMgtById(id);

		List<JmeterTestCase> cases = jmeterTestCaseService.selectJmeterTestCaseList(new JmeterTestCase());

		final List<JmeterTestCase> relatedCases = jmeterJarMgtService.selectRelatedCases(id.longValue());
		if(CollectionUtils.isNotEmpty(relatedCases)){
			jmeterJarMgt.setRelCaseIdList(relatedCases.stream().map(JmeterTestCase::getId).collect(Collectors.toList()));
		}

		mmap.put("cases",cases);
		mmap.put("jmeterJarMgt", jmeterJarMgt);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存jmx脚本依赖jar包管理
	 */
	@RequiresPermissions("jmeter:jmeterJarMgt:edit")
	@Log(title = "jmx脚本依赖jar包管理", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(@RequestBody JmeterJarMgt jmeterJarMgt)
	{

		if(jmeterJarMgt.getGlobal()!=null && jmeterJarMgt.getGlobal()==1){
			jmeterJarMgt.setRelCaseId(0L);
		}


		jmeterJarCaseRelService.deleteByJarId(jmeterJarMgt.getId());
		List<Long> relCaseIdList = jmeterJarMgt.getRelCaseIdList();
		if(CollectionUtils.isNotEmpty(relCaseIdList)){
			for (Long caseId : relCaseIdList) {
				JmeterJarCaseRel jarCaseRel=new JmeterJarCaseRel();
				jarCaseRel.setRelJarId(jmeterJarMgt.getId().longValue());
				jarCaseRel.setRelCaseId(caseId);
				jmeterJarCaseRelService.insertJmeterJarCaseRel(jarCaseRel);
			}
		}

		return toAjax(jmeterJarMgtService.updateJmeterJarMgt(jmeterJarMgt));
	}
	
	/**
	 * 删除jmx脚本依赖jar包管理
	 */
	@RequiresPermissions("jmeter:jmeterJarMgt:remove")
	@Log(title = "jmx脚本依赖jar包管理", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(jmeterJarMgtService.deleteJmeterJarMgtByIds(ids));
	}


	/**
	 * uploadjmx
	 * @author Seagull
	 * @date 2019年7月26日
	 */
	@PostMapping("/uploadJar")
	@ResponseBody
	public AjaxResult uploadJar(@RequestParam("file") MultipartFile file ) {
		AjaxResult ajaxResult= AjaxResult.success();

		try {
			if (!file.isEmpty()) {

				File jarFile = FileUploadUtils.uploadJar(jmeterConfig.getLibDir(), file);
				ajaxResult.put("path",jarFile.getAbsolutePath());
				return ajaxResult;

			}else{
				return error("文件为空");
			}
		} catch (Exception e) {
			return error(e.getMessage());
		}
	}

}
